//
//  RHHouserViewController.swift
//  IMF
//
//  Created by 黄瑞东 on 2018/9/12.
//  Copyright © 2018年 imf. All rights reserved.
//

import UIKit
import TangramKit
import URLNavigator
import SVProgressHUD

class RHHouserViewController: RHRootLayoutController,UISearchBarDelegate, UICollectionViewDataSource,UICollectionViewDelegate{
    
    var searchBarView: UIView?
    var searchBar: UISearchBar?
    var collectionView: UICollectionView?
    let width = UIScreen.main.bounds.size.width//获取屏幕宽
    let height = UIScreen.main.bounds.size.height//获取屏幕高
    var recentlyData = NSMutableArray()
    var hotData = NSMutableArray()
    var model = RHHotCityModel()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.title = NSLocalizedString("HousesTitle", comment: "")
        loadSearchBarView()
        loadCollectionView()
    }
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        if RHAppUserProfile.sharedInstance.hasLoggedIn() && self.hotData.count == 0{
            loadHotCity()
        }
    }
    
    func loadHotCity() {
//        recentlyData.add("当前城市")
        SVProgressHUD.show()
        RHAPIManager.sharedInstance.doHotCity(result: { [weak self] (msg, data) in
            guard let weakSelf = self else { return }
            SVProgressHUD.dismiss()
            weakSelf.model = data as! RHHotCityModel
            for item in weakSelf.model.data!{
                weakSelf.hotData.add(item.enName as Any)
            }
            weakSelf.collectionView?.reloadData()
        }) { (code, message) in
            SVProgressHUD.dismiss()
            SVProgressHUD.showInfo(withStatus: message)
        }
    }

    func loadSearchBarView() {
        self.searchBarView = UIView(frame: CGRect(x: 20, y: 7, width: UIScreen.main.bounds.width - 40, height: 40))
        self.searchBarView?.backgroundColor = .clear
        self.searchBarView?.layer.masksToBounds = true
        self.searchBarView?.layer.cornerRadius = 5
        
        self.searchBarView?.layer.borderColor = UIColor.clear.cgColor
        self.searchBar =  UISearchBar(frame: CGRect(x: 0, y: 0, width: self.searchBarView!.frame.width, height: self.searchBarView!.frame.height))
        self.searchBar?.barTintColor = UIColor.white
        self.searchBar?.tintColor = RHAppSkinColor.sharedInstance.secondaryTextColor;
        self.searchBar?.layer.borderColor = RHAppSkinColor.sharedInstance.placeholderTextColor.cgColor;
        self.searchBar?.layer.borderWidth = 1.0
        self.searchBar?.layer.cornerRadius = 5
        self.searchBar?.placeholder =  NSLocalizedString("SearchCity", comment: "")
        self.searchBar?.delegate = self
        addTapGesture(searchBar: self.searchBar!)
        let searchTextField: UITextField = self.searchBar?.value(forKey: "searchField") as! UITextField
        searchTextField.font = UIFont.systemFont(ofSize: 15.0)
        searchTextField.isEnabled = false
        self.searchBarView?.addSubview(self.searchBar!)
        self.view.addSubview(self.searchBarView!)
    }
    
    func addTapGesture(searchBar: UISearchBar){
        searchBar.isUserInteractionEnabled = true
        let tapGesture = UITapGestureRecognizer(target: self, action: #selector(searchBarClick))
        tapGesture.numberOfTapsRequired = 1
        searchBar.addGestureRecognizer(tapGesture)
    }
    
    func loadCollectionView(){
        let layout = UICollectionViewFlowLayout()
        layout.itemSize = CGSize(width: width/3 - 20, height: 40)
        layout.headerReferenceSize = CGSize.init(width: width, height: 40)
        
        self.collectionView  = UICollectionView(frame: CGRect(x: 10, y: 50, width: width - 20, height: height - 50), collectionViewLayout: layout)
        self.collectionView! .register(RHCityCollectionViewCell.self, forCellWithReuseIdentifier:"cell")
        self.collectionView! .register(RHCityCollectionReusableView.self, forSupplementaryViewOfKind:UICollectionElementKindSectionHeader, withReuseIdentifier: headerIdentifier)
        self.collectionView?.backgroundColor = RHAppSkinColor.sharedInstance.viewBackgroundColor
        self.view.addSubview(self.collectionView!)
        self.collectionView?.dataSource = self
        self.collectionView?.delegate = self
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return hotData.count
//        return section == 0 ? recentlyData.count : hotData.count
    }
    
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return 1
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! RHCityCollectionViewCell
//        cell.titleButton?.setTitle(indexPath.section == 0 ? recentlyData[indexPath.row] as? String : hotData[indexPath.row] as? String, for: .normal)
        cell.titleButton?.setTitle(hotData[indexPath.row] as? String, for: .normal)
        cell.titleButton?.tag = indexPath.row
        cell.titleButton?.addTarget(self, action: #selector(titleButtonClick(_:)), for:.touchUpInside)
        return cell
    }
    
    @objc func titleButtonClick(_ button:UIButton) {
        let vc = RHHousesListController()
        vc.cityName = self.model.data![button.tag].enName
        self.navigationController?.pushViewController(vc, animated: true)
//        self.present(RHCustomNavigationController(rootViewController: vc), animated: true, completion: nil)
    }
    
    func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
        let headerView : RHCityCollectionReusableView = collectionView.dequeueReusableSupplementaryView(ofKind: UICollectionElementKindSectionHeader, withReuseIdentifier: headerIdentifier, for: indexPath) as! RHCityCollectionReusableView
        
        if kind == UICollectionElementKindSectionHeader{
            headerView.label.text = NSLocalizedString("HotCityText", comment: "")

//            headerView.label.text = indexPath.section == 0 ? NSLocalizedString("LocationText", comment: "") : NSLocalizedString("HotCityText", comment: "")
        }
        return headerView
    }
    
    @objc fileprivate func searchBarClick(titleButton: UIButton){
        self.present(RHCustomNavigationController(rootViewController: RHHousesSearchViewController()), animated: false, completion: nil)
    }
}
